package com.shushan.permission;

import android.app.KeyguardManager;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.android.permission.FloatPermissionUtil;
import com.android.permission.rom.RomType;
import com.android.permission.rom.RomUtils;
import com.shushan.base.BaseActivity;
import com.shushan.base.Constants;
import com.shushan.base.ScreenManager;
import com.shushan.receiver.LockAdminReceiver;
import com.shushan.shushanbao.R;
import com.shushan.ui.CustomDialog;
import com.shushan.util.OpenSettingUtils;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.SystemUtils;
import com.shushan.util.ToolUtils;

import static com.android.permission.rom.RomType.EMUI_ROM;

/**
 * @ClassName: PermissionMainActivity
 * @Desciption: 权限主界面
 * @author: yichaohua
 * @date: 2018-05-08
 */
public class PermissionMainActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "PermissionMainActivity";

    private RelativeLayout closeLockLayout;
    private RelativeLayout windowLayout;
    private RelativeLayout adminEnableLayout;

    private Button completeButton;
    private Button windowButton;
    private Button closeLockButton;
    private Button adminEnableButton;
    private Button usageButton;
    private Button powerManagerButton;
    private Button finishButton;

    private ImageView completedImg;
    private ImageView windowImg;
    private ImageView usageImg;
    private ImageView adminEnableImg;
    private ImageView closeLockImg;
    private ImageView closePowerImg;

    private boolean isOpenComplete = false;
    private boolean isOpneWindow = false;
    private boolean isColoseLock = false;
    private boolean isAdminEnable = true;
    private boolean isUsageable = false;
    private boolean isPowerClose = false;

    private DevicePolicyManager dpm;
    private ComponentName adminComponent;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initWindow();

        setContentView(R.layout.permission_main_activity);

        dpm = (DevicePolicyManager) getSystemService(DEVICE_POLICY_SERVICE);
        adminComponent = new ComponentName(this, LockAdminReceiver.class);

        RomType romType = RomUtils.getRomType(this);
        Log.i(TAG,"romType=" + romType.toString());

        initView(romType);

        initData(romType);
    }

    private void initWindow(){
        ScreenManager screenManager = ScreenManager.getInstance();
        screenManager.setStatusBar(true, this);
        screenManager.setScreenRoate(true, this);
        screenManager.setFullScreen(false, this);
    }

    private void initView(RomType romType) {
        usageButton = findViewById(R.id.permission_main_usage_btn);
        usageButton.setOnClickListener(this);
        usageImg = findViewById(R.id.permission_main_usage_img);
        adminEnableLayout = findViewById(R.id.permission_main_admin_enable_layout);
        adminEnableButton = findViewById(R.id.permission_main_admin_enable_btn);
        adminEnableButton.setOnClickListener(this);
        adminEnableImg = findViewById(R.id.permission_main_admin_enable_img);
        powerManagerButton = findViewById(R.id.permission_main_power_manager_btn);
        powerManagerButton.setOnClickListener(this);
        closePowerImg = findViewById(R.id.permission_main_power_manager_img);
        windowLayout = findViewById(R.id.permission_main_open_window_layout);
        completedImg = findViewById(R.id.permission_main_open_completed_img);
        windowImg = findViewById(R.id.permission_main_open_window_img);
        closeLockImg = findViewById(R.id.permission_main_close_lock_img);
        closeLockLayout = findViewById(R.id.permission_main_close_lock_layout);
        completeButton = findViewById(R.id.permission_main_open_completed_btn);
        completeButton.setOnClickListener(this);
        windowButton = findViewById(R.id.permission_main_open_window_btn);
        windowButton.setOnClickListener(this);
        closeLockButton = findViewById(R.id.permission_main_close_lock_btn);
        closeLockButton.setOnClickListener(this);
        finishButton = findViewById(R.id.permission_main_finish_btn);
        finishButton.setOnClickListener(this);

        if(romType == EMUI_ROM  && RomUtils.getEmuiLeval(this) >= 14){
            completeButton.setVisibility(View.GONE);
            completedImg.setVisibility(View.GONE);
            isOpenComplete = true;
        }
    }

    private void initData(RomType romType) {
        if(romType == RomType.SMARTISAN_ROM){
            powerManagerButton.setText("开启后台常驻");
        }

        if(romType == RomType.SAMSUNG_ROM || romType == RomType.FLYME_ROM){
            isPowerClose = true;
            powerManagerButton.setVisibility(View.GONE);
            closePowerImg.setVisibility(View.GONE);
        }

        if(!(romType == RomType.FUNTOUCHOS_ROM || romType == RomType.SMARTISAN_ROM)){
            if(FloatPermissionUtil.checkPermission(this)){
                isOpneWindow = true;
                windowImg.setVisibility(View.VISIBLE);
                windowButton.setOnClickListener(null);
            }else {
                isOpneWindow = false;
                windowImg.setVisibility(View.GONE);
                windowButton.setOnClickListener(this);
            }
        }


        KeyguardManager mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        if(!mKeyguardManager.isKeyguardSecure()){
            isColoseLock = true;
            closeLockImg.setVisibility(View.VISIBLE);
            closeLockButton.setOnClickListener(null);
            closeLockLayout.setVisibility(View.GONE);
        }else {
            isColoseLock = false;
            closeLockImg.setVisibility(View.GONE);
            closeLockButton.setOnClickListener(this);
            closeLockLayout.setVisibility(View.VISIBLE);
        }

//        if (dpm.isAdminActive(adminComponent)) {
//            isAdminEnable = true;
//            adminEnableImg.setVisibility(View.VISIBLE);
//            adminEnableButton.setOnClickListener(null);
//        }else {
//            isAdminEnable = false;
//            adminEnableImg.setVisibility(View.GONE);
//            adminEnableButton.setOnClickListener(this);
//        }

        if(SystemUtils.checkUsagePermission(this)){
            isUsageable = true;
            usageImg.setVisibility(View.VISIBLE);
            usageButton.setOnClickListener(null);
        }else {
            isUsageable = false;
            usageImg.setVisibility(View.GONE);
            usageButton.setOnClickListener(this);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.permission_main_open_completed_btn:
                startActivityForResult(OpenCompleteActivity.class);
                break;
            case R.id.permission_main_open_window_btn:
                startActivityForResult(OpenWindowActivity.class);
                break;
            case R.id.permission_main_close_lock_btn:
                startActivityForResult(CloseSysLockActivity.class);
                break;
            case R.id.permission_main_admin_enable_btn:
                checkAndEnableAdmin();
                break;
            case R.id.permission_main_usage_btn:
                startActivityForResult(OpenUsageActivity.class);
                break;
            case R.id.permission_main_power_manager_btn:
                startActivityForResult(PowerManagerActivity.class);
                break;
            case R.id.permission_main_finish_btn:
                onFinishSet();
                break;
            default:
                break;
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                return true;
        }
        return super.onKeyDown(keyCode, event);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.i(TAG,"onActivityResult requestCode=" + requestCode + " resultCode=" + resultCode);

        if(requestCode == 150){
            if (dpm.isAdminActive(adminComponent)) {
                isAdminEnable = true;
                adminEnableImg.setVisibility(View.VISIBLE);
            }
        }else {
            if(resultCode == 200){
                isOpenComplete = true;
                completedImg.setVisibility(View.VISIBLE);
            }else if(resultCode == 300){
                RomType romType = RomUtils.getRomType(this);
                if(!(romType == RomType.FUNTOUCHOS_ROM || romType == RomType.SMARTISAN_ROM)){
                    if(FloatPermissionUtil.checkPermission(this)){
                        isOpneWindow = true;
                        windowImg.setVisibility(View.VISIBLE);
                    }else {
                        isOpneWindow = false;
                        windowImg.setVisibility(View.GONE);
                    }
                }else {
                    isOpneWindow = true;
                    windowImg.setVisibility(View.VISIBLE);
                }


            }else if(resultCode == 400){
                KeyguardManager mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
                if(!mKeyguardManager.isKeyguardSecure()){
                    isColoseLock = true;
                    closeLockImg.setVisibility(View.VISIBLE);
                }else {
                    isColoseLock = false;
                    closeLockImg.setVisibility(View.GONE);
                }
            }else if(resultCode == 500){
                isPowerClose = true;
                closePowerImg.setVisibility(View.VISIBLE);
            }else if(resultCode == 600){
                if(SystemUtils.checkUsagePermission(this)){
                    isUsageable = true;
                    usageImg.setVisibility(View.VISIBLE);
                }else {
                    isUsageable = false;
                    usageImg.setVisibility(View.GONE);
                }
            }
        }

    }

    private void onFinishSet() {

        if(!isPowerClose){
            RomType romType = RomUtils.getRomType(this);
            if(romType == RomType.SMARTISAN_ROM){
                showSmartPowerWarnDialog();
            }else {
                showPowerWarnDialog();
            }

            return;
        }

        if(!isOpneWindow){
            showWindowWarnDialog();
            return;
        }

        if(!isOpenComplete){
            showCompleteWarnDialog();
            return;
        }

        if(!isColoseLock){
            showColoseLockWarnDialog();
            return;
        }

        SharedPreferencesUtils.setBooleanDate(Constants.MAIN_PERMISSION_HAS_SET_SHAREPREFERS_KEY,true);

        onBackAction(600);
    }

    private void showCompleteWarnDialog() {
        new CustomDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("发现您尚未开启自启动，手机重启将导致无法控制小孩玩手机，是否去设置？")
                .setNegativeButton("放弃", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        onBackAction(250);

                    }
                })
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        startActivityForResult(OpenCompleteActivity.class);

                    }
                })
                .create().show();
    }

    private void showWindowWarnDialog() {
        new CustomDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("发现您尚未开启悬浮窗权限，将导致无法开启锁屏，是否去设置？")
                .setNegativeButton("放弃", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        onBackAction(250);

                    }
                })
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        startActivityForResult(OpenWindowActivity.class);

                    }
                })
                .create().show();
    }

    private void showColoseLockWarnDialog() {
        new CustomDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("发现系统也设置了锁屏，为了避免解锁两次建议您关闭系统锁屏，是否去设置？")
                .setNegativeButton("放弃", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        onBackAction(250);

                    }
                })
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        startActivityForResult(CloseSysLockActivity.class);

                    }
                })
                .create().show();
    }

    private void showPowerWarnDialog() {
        new CustomDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("发现您尚未关闭省电模式，将导致应用无法正常运行，是否去设置？")
                .setNegativeButton("放弃", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        onBackAction(250);

                    }
                })
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        startActivityForResult(PowerManagerActivity.class);

                    }
                })
                .create().show();
    }

    private void showSmartPowerWarnDialog() {
        new CustomDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("发现您尚未开启后台常驻，将导致应用无法正常运行，是否去设置？")
                .setNegativeButton("放弃", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        onBackAction(250);

                    }
                })
                .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        startActivityForResult(PowerManagerActivity.class);

                    }
                })
                .create().show();
    }

    private void checkAndEnableAdmin() {
        if (!dpm.isAdminActive(adminComponent)) {
            Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, adminComponent);
            intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, this.getString(R.string.device_admin_hint));
            startActivityForResultAllow(intent, 150);
        } else {
            Log.i(TAG,"设备管理器已激活");
        }
    }
}
